<template>
  <div class="project-manage-bg">
    <div class="project-manage-layout">
      <!-- 左侧文件夹导航 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <span class="sidebar-title">文件夹</span>
          <el-tooltip content="创建文件夹" placement="top">
            <el-button class="sidebar-add-btn" circle size="small" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <div class="sidebar-list">
          <div v-if="folderStack.length > 0" class="sidebar-item" @click="handleBack">
            <el-icon><ArrowLeft /></el-icon>
            <span class="sidebar-item-name">返回上一级</span>
          </div>
          <template v-if="currentFolders.length > 0">
            <div
              v-for="folder in currentFolders"
              :key="folder.id"
              :class="['sidebar-item', { active: currentFolder && currentFolder.id === folder.id }]"
              @click.stop="selectFolder(folder)"
              @dblclick.stop="handleFolderClick(folder)"
            >
              <el-icon style="cursor:pointer;"><Folder /></el-icon>
              <span class="sidebar-item-name">{{ folder.name }}</span>
              <el-icon style="margin-left:auto;color:#409eff;cursor:pointer;" @click.stop="handleEditFolder(folder)">
                <el-icon-edit />
              </el-icon>
              <el-icon style="margin-left:8px;color:#f56c6c;cursor:pointer;" @click.stop="handleDeleteFolder(folder)">
                <el-icon-delete />
              </el-icon>
            </div>
          </template>
          <div v-else class="sidebar-empty">
            <el-icon style="font-size:32px;color:#bcbcff;margin-bottom:8px;"><Folder /></el-icon>
            <div style="color:#bbb;font-size:15px;">空空如也</div>
          </div>
        </div>
      </div>
      <!-- 右侧主内容区 -->
      <div class="main-content">
        <div class="main-content-header">
          <h5>{{ currentFolder?.name || '所有项目' }}</h5>
          <el-button type="primary" @click="handleShowCreateProjectDialog" class="main-create-btn">+ 创建项目</el-button>
        </div>
        <div class="main-card-list">
          <div v-if="projects.length === 0" class="main-card">
            <div class="main-card-icon">
              <el-icon style="font-size:48px;color:#8b5cf6;background:#ececff;border-radius:50%;padding:18px;">
                <Document />
              </el-icon>
            </div>
            <div class="main-card-title">{{ currentFolder?.name || '暂无项目' }}</div>
            <div class="main-card-desc">点击"创建项目"按钮开始你的第一个项目</div>
            <el-button type="primary" @click="handleShowCreateProjectDialog" plain class="main-card-btn">+ 创建项目</el-button>
          </div>
          <div v-else class="project-list">
            <div v-for="item in projects" :key="item.id" class="project-card" @click="handleProjectClick(item)">
              <img v-if="item.coverImage" :src="item.coverImage" class="project-card-cover" />
              <div class="project-card-content">
                <div class="project-card-title">{{ item.name }}</div>
                <div class="project-card-desc">{{ item.description || '无描述' }}</div>
                <div class="project-card-stats">
                  <span>预算项：{{ item.budgetItem || 0 }}</span>
                  <span>总预算：{{ item.budgetSum || 0 }}元</span>
                </div>
                <div class="project-card-footer">
                  <span class="project-card-time">最后编辑：{{ item.updateTime }}</span>
                  <div class="project-card-actions">
                    <el-icon style="margin-right:12px;cursor:pointer;" @click.stop="handleMoveProject(item)"><Folder /></el-icon>
                    <el-icon style="margin-right:12px;cursor:pointer;" @click.stop="handleEditProjectDialog(item)"><el-icon-edit /></el-icon>
                    <el-icon style="color:#f56c6c;cursor:pointer;" @click.stop="handleDeleteProject(item)"><el-icon-delete /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部状态栏 -->
    <div class="footer-bar">
      <span>项目: {{ projects.length }}</span>
      <span>预算项: 0</span>
      <span>{{ now }}</span>
    </div>
    <!-- 页面底部加上弹窗组件 -->
    <CreateFolderDialog v-model="showCreateDialog" @create="handleCreateFolder" />
    <CreateProjectDialog
      v-model="showProjectDialog"
      :folderOptions="folderOptions"
      :defaultFolder="defaultProjectFolder"
      :mode="dialogMode"
      :projectData="editProject"
      @create="handleCreateProject"
      @edit="handleEditProject"
    />
    <!-- 新增/编辑文件夹弹窗 -->
    <el-dialog v-model="showEditDialog" title="修改文件夹名称" width="340px">
      <el-input v-model="editFolderName" placeholder="请输入新名称" />
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :disabled="!editFolderName" @click="confirmEditFolder">保存</el-button>
      </template>
    </el-dialog>
    <!-- 移动项目弹窗 -->
    <el-dialog v-model="showMoveDialog" title="移动到文件夹" width="340px">
      <el-tree-select
        v-model="moveTargetFolder"
        :data="folderTree"
        :props="{ label: 'name', value: 'id', children: 'children' }"
        placeholder="请选择目标文件夹"
        style="width:100%"
        check-strictly
        node-key="id"
        :default-expand-all="true"
      />
      <template #footer>
        <el-button @click="showMoveDialog = false">取消</el-button>
        <el-button type="primary" :disabled="!moveTargetFolder" @click="confirmMoveProject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ArrowLeft, Delete as ElIconDelete, Document, Edit as ElIconEdit, Folder, Plus} from '@element-plus/icons-vue'
import CreateFolderDialog from '@/components/CreateFolderDialog.vue'
import CreateProjectDialog from '@/components/CreateProjectDialog.vue'
import {addDirectory, deleteDirectory, getDirectoryList, updateDirectory} from '@/api/directoryApi'
import {ElMessage, ElMessageBox} from 'element-plus'
import {addProject, deleteProject, getProjectList, updateProject} from '@/api/projectApi'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const router = useRouter()
const store = useStore()
const now = new Date().toLocaleString('zh-CN', { hour12: false })
const showCreateDialog = ref(false)
const showProjectDialog = ref(false)
const showEditDialog = ref(false)
const editFolderName = ref('')
const editFolder = ref(null)
const folderOptions = ref([])
const currentFolders = ref([])     // 当前显示的子目录
const currentFolder = ref(null)    // 当前所在目录对象
const folderStack = ref([])        // 用于返回上一级
const projects = ref([])
const showMoveDialog = ref(false)
const moveProjectId = ref(null)
const moveTargetFolder = ref(null)
const dialogMode = ref('create')
const editProject = ref(null)
const folderTree = ref([])
const defaultProjectFolder = ref(null)

const queyDirectory = reactive({
  userId: store.getters.getUserId,
})

onMounted(async () => {
    const res = await getDirectoryList(queyDirectory)
    if (Array.isArray(res)) {
      currentFolders.value = res
      currentFolder.value = res ? res[0] : null;
      folderStack.value = []
      if(currentFolder.value){
        await fetchProjects(currentFolder.value.id)
      }
    }
})

function handleFolderClick(folder) {
  folderStack.value.push(folder)
  currentFolder.value = folder
  currentFolders.value = Array.isArray(folder.children) ? folder.children : []
  fetchProjects(folder.id)
}

async function handleBack() {
  const prev = folderStack.value.pop()
  currentFolder.value = prev;
  if(prev){
    queyDirectory.parentId = prev.parentId;
  }else{
    queyDirectory.parentId = null;
  }
  currentFolders.value = await getDirectoryList(queyDirectory);
  await fetchProjects(prev ? prev.id : null)
}

async function handleCreateFolder(data) {
    // data: { name, color }
    const parentId = currentFolder.value ? currentFolder.value.id : null
    await addDirectory({ name: data.name, parentId,userId:1 })
    ElMessage.success('新建文件夹成功')
    // 刷新当前目录
    await refreshCurrentFolders()
}

// 处理新建项目
async function handleCreateProject(data) {
  data.userId = store.getters.getUserId;
  console.log(data)
  const rs = await addProject(data);
  ElMessage.success('创建成功')
  await fetchProjects(data.directoryId)
}

async function handleDeleteFolder(folder) {
    await ElMessageBox.confirm(`确定要删除文件夹"${folder.name}"吗？`, '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteDirectory(folder.id)
    ElMessage.success('删除成功')
    // 刷新当前目录
    if (currentFolder.value === null) {
      // 根目录
      currentFolders.value = currentFolders.value.filter(f => f.id !== folder.id)
    } else {
      currentFolder.value.children = (currentFolder.value.children || []).filter(f => f.id !== folder.id)
      currentFolders.value = currentFolders.value.filter(f => f.id !== folder.id)
    }
}

function handleEditFolder(folder) {
  editFolder.value = folder
  editFolderName.value = folder.name
  showEditDialog.value = true
}

async function confirmEditFolder() {
    await updateDirectory({ ...editFolder.value, name: editFolderName.value })
    ElMessage.success('修改成功')
    showEditDialog.value = false
    await refreshCurrentFolders()
}

async function refreshCurrentFolders() {
  // 重新获取目录树并刷新当前目录
  const res = await getDirectoryList(queyDirectory)
  currentFolder.value = res ? res[0] : null
  currentFolders.value = Array.isArray(res) ? res : []
}

// 查询项目列表
async function fetchProjects(folderId) {
  try {
    const params = { directoryId: folderId,userId:store.getters.getUserId }
    const res = await getProjectList(params)
    projects.value = Array.isArray(res) ? res : []
    console.log(projects.value)
  } catch (e) {
    projects.value = []
  }
}

function selectFolder(folder) {
  // 如果当前已选中且点击的是同一个文件夹，则取消选中
  if (currentFolder.value && currentFolder.value.id === folder.id) {
    currentFolder.value = null;
    fetchProjects(null); // 显示所有项目
  } else {
    currentFolder.value = folder;
    fetchProjects(folder.id);
  }
}

async function handleMoveProject(project) {
  moveProjectId.value = project.id
  moveTargetFolder.value = null
  // 动态获取最新文件夹树
  try {
    const res = await getDirectoryList(queyDirectory)
    if (Array.isArray(res)) {
      folderTree.value = res
    }
  } catch (e) {
    folderTree.value = []
  }
  showMoveDialog.value = true
}

async function confirmMoveProject() {
    await updateProject({ id: moveProjectId.value, directoryId: moveTargetFolder.value })
    ElMessage.success('移动成功')
    showMoveDialog.value = false
    await fetchProjects(currentFolder.value ? currentFolder.value.id : null)
}

function handleEditProjectDialog(project) {
  dialogMode.value = 'edit';
  editProject.value = { ...project };
  showProjectDialog.value = true;
}

async function handleDeleteProject(project) {
    await ElMessageBox.confirm(`确定要删除项目"${project.name}"吗？`, '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteProject(project.id)
    ElMessage.success('删除成功')
    await fetchProjects(currentFolder.value ? currentFolder.value.id : null)
}

async function handleShowCreateProjectDialog() {
  const dirList = await getDirectoryList({ userId: 1 });
  if (!dirList || dirList.length === 0) {
    ElMessage.warning('请先创建文件夹');
    return;
  }
  // 自动映射当前选中的文件夹
  defaultProjectFolder.value = currentFolder.value ? currentFolder.value.id : null;
  dialogMode.value = 'create';
  editProject.value = null;
  showProjectDialog.value = true;
}

async function handleEditProject(data) {
    await updateProject(data)
    ElMessage.success('修改成功')
    showProjectDialog.value = false
    await fetchProjects(currentFolder.value ? currentFolder.value.id : null)
}

function handleProjectClick(item) {
  router.push({
    path: '/plat-tools/budget-form',
    query: {
      templateId: item.templateId,
      projectId: item.id
    }
  })
}

</script>

<style lang="less" scoped>
.project-manage-bg {
  background-color: #fefefe;
  height: 100%;

  .project-manage-layout {
    background-color: #fefefe;
    display: flex;
    gap: 20px;

    .sidebar {
      width: 220px;
      background: transparent;
      padding: 20px 0 0 24px;

      .sidebar-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
        margin-bottom: 12px;

        .sidebar-title {
          font-size: 16px;
          color: #888;
          font-weight: 500;
          margin-right: 0;
        }

        .sidebar-add-btn {
          background: #ececff;
          color: #5c5cff;
          border: none;
          font-size: 18px;
          box-shadow: 0 2px 8px #5c5cff22;
          margin-left: 4px;
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background 0.2s;

          &:hover {
            background: #d6d6ff;
          }
        }
      }

      .sidebar-list {
        display: flex;
        flex-direction: column;
        gap: 6px;

        .sidebar-item {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 8px 18px;
          border-radius: 12px;
          font-size: 16px;
          color: #444;
          cursor: pointer;
          background: transparent;
          transition: background 0.18s, color 0.18s, box-shadow 0.18s;
          position: relative;
          min-height: 40px;
          margin: 2px 0;

          &:hover {
            background: #ececff;
            color: #6366f1;
            box-shadow: 0 2px 8px #6366f122;
          }

          &.active {
            color: #fff;
            background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
            font-weight: 600;
            box-shadow: 0 4px 16px #6366f144;
          }

          .el-icon {
            font-size: 20px;
            color: inherit;
            transition: color 0.18s;
          }

          .sidebar-item-name {
            min-width: 64px;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }

    .main-content {
      flex: 1 1 0%;
      min-width: 0;
      width: auto;
      position: relative;
      padding: 0 24px 0 0;
      display: flex;
      flex-direction: column;
      align-items: stretch;
      justify-content: flex-start;

      .main-content-header {
        display: flex;
        -webkit-box-pack: justify;
        -webkit-box-align: center;
        margin-bottom: 24px;
        margin-top: 24px;
        align-items: center;
        justify-content: space-between;

        h5{
          margin: 0;
          font-size: 1.5rem;
          line-height: 1.334;
          font-weight: 600;
          background: linear-gradient(135deg, rgb(99, 102, 241) 0%, rgb(139, 92, 246) 100%) text;
          -webkit-text-fill-color: transparent;
        }

        .el-button.main-create-btn {
          background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
          color: #fff;
          border: none;
          line-height: 1.5;
          border-radius: 10px;
          font-size: 16px;
          font-weight: 500;
          padding: 22px 24px;
          box-shadow: 0 2px 12px #6366f122;
          transition: background 0.18s, box-shadow 0.18s;
        }
        .el-button.main-create-btn:hover {
          background: linear-gradient(90deg, #7c3aed 0%, #6366f1 100%);
          box-shadow: 0 4px 16px #6366f144;
        }
      }

      .main-card-list {
      }

      .main-card {
        background: linear-gradient(135deg, #f5f6ff 0%, #ececff 100%);
        border-radius: 24px;
        border: 1.5px dashed #bcbcff;
        min-height: 340px;
        min-width: 70vw;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 56px 0;
        margin-left: 20px;
        margin-top: 32px;
        box-sizing: border-box;

        .main-card-icon {
          margin-bottom: 18px;
          width: 80px;
          height: 80px;
          background: #ececff;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;

          .el-icon {
            font-size: 44px;
            color: #8b5cf6;
          }
        }

        .main-card-title {
          font-size: 22px;
          font-weight: bold;
          color: #444;
          margin-bottom: 8px;
        }

        .main-card-desc {
          color: #888;
          font-size: 15px;
          margin-bottom: 18px;
        }

        .el-button.main-card-btn {
          border-radius: 10px;
          color: #fff;
          background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
          border: none;
          font-weight: 500;
          font-size: 16px;
          padding: 22px 24px;
          box-shadow: 0 2px 12px #6366f122;
          margin-top: 8px;
          transition: background 0.18s, box-shadow 0.18s;
        }
        .el-button.main-card-btn:hover {
          background: linear-gradient(90deg, #7c3aed 0%, #6366f1 100%);
          box-shadow: 0 4px 16px #6366f144;
        }
      }

      .project-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 32px;
        align-items: stretch;
      }

      .project-card {
        display: flex;
        flex-direction: column;
        height: 260px;
        background: #fff;
        border-radius: 18px;
        box-shadow: 0 4px 24px #6366f122;
        border: 1.5px solid #ececff;
        overflow: hidden;
        margin-bottom: 0;
        transition: box-shadow 0.18s, transform 0.18s;
        position: relative;
        &:hover {
          box-shadow: 0 8px 32px #6366f144;
          transform: translateY(-2px) scale(1.02);
        }
      }

      .project-card-cover {
        width: 100%;
        height: 100px;
        object-fit: cover;
        border-top-left-radius: 18px;
        border-top-right-radius: 18px;
        background: #f5f6ff url('https://sky-story.oss-cn-beijing.aliyuncs.com/a2c0abae-a7bf-43dd-8948-b0f4910211ec.webp') center/cover no-repeat;
        border-bottom: 1px solid #ececff;
        display: block;
      }
      .project-card-cover:empty {
        background: #f5f6ff url('https://sky-story.oss-cn-beijing.aliyuncs.com/a2c0abae-a7bf-43dd-8948-b0f4910211ec.webp') center/cover no-repeat;
      }

      .project-card-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 12px 14px 8px 14px;
      }

      .project-card-title {
        font-size: 22px;
        font-weight: 700;
        color: #6366f1;
        margin-bottom: 6px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .project-card-desc {
        color: #888;
        font-size: 15px;
        margin-bottom: 12px;
        min-height: 20px;
        max-height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .project-card-stats {
        display: flex;
        gap: 18px;
        font-size: 14px;
        color: #555;
        margin-bottom: 10px;
      }

      .project-card-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-top: 1px solid #f0f0f0;
        padding-top: 10px;
        margin-top: auto;
      }

      .project-card-time {
        color: #bbb;
        font-size: 13px;
      }

      .project-card-actions {
        display: flex;
        align-items: center;
      }
    }
  }
}

.footer-bar {
  width: 100vw;
  background: #fff;
  color: #888;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 0 24px;
  height: 38px;
  border-top: 1px solid #ececff;
  position: fixed;
  bottom: 0;
  z-index: 10;
}

.sidebar-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 120px;
  color: #bbb;
  font-size: 15px;
  padding: 24px 0;
  user-select: none;
}

/* 响应式：小屏2列、超小屏1列 */
@media (max-width: 900px) {
  .main-card-list {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 600px) {
  .main-card-list {
    grid-template-columns: 1fr;
  }
}
</style>